package com.alibaba.aliper.agent.sys;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.aliper.agent.util.FileReader;

public class CpuState {
	public CpuState(){
		String content = FileReader.readFromFile(CPU_STATE_FILE);
		for(cpuCount = 0;content.contains("cpu"+cpuCount);++cpuCount);
		data = new int[cpuCount+1][7];
		temp = new int[cpuCount+1][7];
		extract(content);
		time = System.currentTimeMillis();
	}
	int cpuCount = 1;
	int[][] data = null;
	int[][] temp = null;
	long time = 0;
	public static final String CPU_STATE_FILE="/proc/stat";

	private void extract(String content){
		Matcher matcher = pattern.matcher(content);
		for(int i = 0;matcher.find();++i){
			for(int j = 0; j < 7; ++j)
				data[i][j] = Integer.parseInt(matcher.group(j+1));
		}
	}
	public long getTime(){
		return time;
	}
	public int getCpuCount(){
		return this.cpuCount;
	}
	public int getUser(int index) {
		return data[index][0];
	}

	public int getNice(int index) {
		return data[index][1];
	}

	public int getSystem(int index) {
		return data[index][2];
	}

	public int getIdle(int index) {
		return data[index][3];
	}

	public int getIowait(int index) {
		return data[index][4];
	}

	public int getIrq(int index) {
		return data[index][5];
	}

	public int getSoftirq(int index) {
		return data[index][6];
	}
	
	public CpuPercentage subtract(CpuState state){
		double[][] perData = new double[data.length][data[0].length];
		for(int i = 0; i < data.length ; ++i){
			int sum = 0;
			for(int j = 0; j < data[0].length ; ++j){
				temp[i][j] = data[i][j] - state.data[i][j];
				sum += temp[i][j];
			}
			for(int j = 0; j < data[0].length ; ++j){
				perData[i][j] = (double)temp[i][j] / (double)sum;
			}
		}
		return new CpuPercentage(perData);
	}
	
	private static final Pattern pattern = Pattern.compile("cpu[0-9]*\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)");
	
}
